'''
Created on Mar 3, 2010

@author: wangyongtao
'''
import os
import logging
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp import template 

DEBUG = True
NS_SETTING = 'setting'
CACHE_DURATION = 86400

COLUMN_TITLE_INTRO = 'column_intro'
COLUMN_TITLE_GUIDE = 'column_guide'
COLUMN_TITLE_MEMBER = 'column_member'
COLUMN_TITLE_CONTACT = 'column_contact'
COLUMN_TITLE_KB = 'column_kb'
COLUMN_TITLE_SUB = 'column_sub'
COLUMN_TITLE_SPECIALIST = 'column_specialist'

class TemplateRequestHandler(webapp.RequestHandler):
    def generate(self, template_name, template_values = {}):
        navitems = columns.get_top_navitems()
        speitems = columns.get_specialist_items(20)
        logging.info('length:%d'%len(navitems))
        values = {
            'navitems': navitems,
            'speitems': speitems,
            'request' : self.request,
            'user' : users.get_current_user(),
            'is_admin': users.is_current_user_admin(),
            'login_url': users.create_login_url(self.request.uri),
            'logout_url': users.create_logout_url('http://%s/' % (self.request.host,)),
            'application_name' : 'Shiyan Hospital',
        }
        values.update(template_values)
        dir = os.path.dirname(__file__)
        path = os.path.join(dir, os.path.join('templates', template_name)) 
        self.response.out.write(template.render(path, values))

class photos(db.Model):
    pkey = db.StringProperty(required=True)
    raw = db.BlobProperty()
    width = db.IntegerProperty()
    height = db.IntegerProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
        
class news(db.Model):
    title = db.StringProperty(required=True)
    content = db.TextProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
class knowledgebase(db.Model):
    title = db.StringProperty(required=True)
    content = db.TextProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
class guestbook(db.Model):
    title = db.StringProperty(required=True)
    name = db.StringProperty()
    pid = db.SelfReferenceProperty()
    reply = db.BooleanProperty(default = False)
    contact = db.StringProperty()
    content = db.TextProperty()
    enabled = db.BooleanProperty(default = True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
class links(db.Model):
    title = db.StringProperty(required=True)
    logo = db.LinkProperty()
    link = db.LinkProperty(required=True)
    enabled = db.BooleanProperty(default = True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
class columns(db.Model):
    cid = db.StringProperty(required=True)
    title = db.StringProperty(required = True)
    pid = db.SelfReferenceProperty()
    url = db.StringProperty()
    content = db.TextProperty()
    subsupport = db.BooleanProperty(default=False)
    specialist = db.BooleanProperty(default = False)
    enabled = db.BooleanProperty(default = True)
    ordervalue = db.IntegerProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
    def get_title_by_cid(self, columnid):
        result = columns.all().filter('cid =', columnid).get()
        if result:
            return result.title
        return None
    
    def get_column_by_cid(self, columnid):
        return columns.all().filter('cid =', columnid).get()
    
    def get_top_navitems(self):
        return columns.all().filter('pid =', None).order('ordervalue').fetch(20, 0)
    
    def get_specialist_items(self, count = 2):
        s = self.get_column_by_cid(COLUMN_TITLE_SPECIALIST)
        if s:
            items = []
            cols = columns.all().filter('pid =', s).order('ordervalue').fetch(count, 0)
            for col in cols:
                if col.subsupport is None or not col.subsupport:
                    items.append(col) 
            return cols
        return None
    
    def add_specialist_item(self, title, content):
        s = self.get_column_by_cid(COLUMN_TITLE_SPECIALIST)
        if s:
            col = columns(cid = COLUMN_TITLE_SUB, title = title, pid = s, content = content, specialist = True)
            col.put()
            return col
        return None
    
    def edit_specialist_item(self, key, title, content):
        col = columns.get(key)
        if col is None:
            return None
        else:
            if col.pid.cid != COLUMN_TITLE_SPECIALIST:
                return None
            else:
                col.title = title
                col.content = content
                col.put()
                return col
        return None
    
    def get_kb_items(self, count = 10):
        s = self.get_column_by_cid(COLUMN_TITLE_KB)
        if s:
            items = []
            cols = columns.all().filter('pid =', s).order('ordervalue').fetch(count, 0)
            for col in cols:
                if col.subsupport is None or not col.subsupport:
                    items.append(col) 
            return cols
        return None
    
    def add_kb_item(self, title, content):
        s = self.get_column_by_cid(COLUMN_TITLE_KB)
        if s:
            col = columns(cid = COLUMN_TITLE_SUB, title = title, pid = s, content = content, specialist = False)
            col.put()
            return col
        return None
    
    def edit_kb_item(self, key, title, content):
        col = columns.get(key)
        if col is None:
            return None
        else:
            if col.pid.cid != COLUMN_TITLE_KB:
                return None
            else:
                col.title = title
                col.content = content
                col.put()
                return col
        return None

    def init(self):
        logging.info('init columns')
        db.delete(columns.all())
        items = [[COLUMN_TITLE_INTRO, 'introduction', False, 1, False],
                 [COLUMN_TITLE_GUIDE, 'guide', False,  2, False],
                 [COLUMN_TITLE_MEMBER, 'members', False, 3, True,],
                 [COLUMN_TITLE_CONTACT, 'contact', False, 6, False],
                 [COLUMN_TITLE_KB, 'kb', False, 5, True],
                 [COLUMN_TITLE_SPECIALIST, 'specialist', True, 4, True], 
                 ]
        for item in items:
            column = columns(cid = item[0], title = item[1], url=item[1], subsupport=item[4], specialist = item[2], ordervalue=int(item[3]))
            column.put()
        return True
        
    get_top_navitems = classmethod(get_top_navitems)
    get_title_by_cid = classmethod(get_title_by_cid)
    get_column_by_cid = classmethod(get_column_by_cid)
    get_specialist_items = classmethod(get_specialist_items)
    add_specialist_item = classmethod(add_specialist_item)
    edit_specialist_item = classmethod(edit_specialist_item)
    get_kb_items = classmethod(get_kb_items)
    add_kb_item = classmethod(add_kb_item)
    edit_kb_item = classmethod(edit_kb_item)
    init = classmethod(init)
    
class members(db.Model):
    name = db.StringProperty(required=True)
    title = db.StringProperty()
    subject = db.StringProperty()
    profile = db.TextProperty()
    portrait = db.BlobProperty(default=None)
    ordervalue = db.IntegerProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
    def get_members(self, count=10):
        return members.all().order('ordervalue').fetch(count, 0)
    
    def add_member(self, name, title, subject, profile, portrait = None):
        s = members.all().filter('name =', name).get()
        if s is None:
            s = members(name = name, title = title, subject = subject, profile = profile, portrait = portrait)
        else:
            s.title = title
            s.subject = subject
            s.profile = profile
            if portrait:
                s.portrait = db.Blob(portrait)
        s.put()
        return s
    
    def edit_member(self, key, name, title, subject, profile, portrait=None):
        s = members.get(key)
        if s is None:
            return None
        else:
            s.title = title
            s.subject = subject
            s.profile = profile
            if portrait:
                s.portrait = db.Blob(portrait)
            s.put()
            return s
        return None
    
    add_member = classmethod(add_member)
    edit_member = classmethod(edit_member)
    get_members = classmethod(get_members)
    
class setting(db.Model):
    title = db.StringProperty(required=False, indexed=True)
    substance = db.TextProperty()
  
    def get(self, name):
        value = memcache.get(name, NS_SETTING)
        if value is not None:
          return value
        else:
          q = setting.all().filter('title =', name)
          if q.count() == 1:
            value = q.get().substance
            memcache.delete(name, namespace=NS_SETTING)
            memcache.set(name, value, time=CACHE_DURATION, namespace=NS_SETTING)
          return value
    get = classmethod(get)

    
    def set(self, name, value):
        q = setting.all().filter('title =', name)
        if q.count() == 1:
          d = q.get()
        else:
          d = setting()
          d.title = name
        d.substance = value
        d.put()
        memcache.delete(name, namespace=NS_SETTING)
        memcache.set(name, d.substance, time=CACHE_DURATION, namespace=NS_SETTING)
    set = classmethod(set)

